package com.example.app.adapter.home;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.app.R;
import com.example.app.viewmodel.home.NewGoodsList;

import java.util.List;

public class NewGoodsListAdapter extends RecyclerView.Adapter<NewGoodsListAdapter.ViewHolder> {
    private Context ctx;
    private List<NewGoodsList> newGoodsLists;
    private OnItemClickListener listener;
    // 添加一个点击监听器接口
    public interface OnItemClickListener {
        void onItemClick(NewGoodsList item);
    }

    public NewGoodsListAdapter(Context ctx, List<NewGoodsList> newGoodsLists,OnItemClickListener listener) {
        this.ctx = ctx;
        this.newGoodsLists = newGoodsLists;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.ctx).inflate(R.layout.adapter_home_newgoodslist,null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Glide.with(this.ctx)
                .load(newGoodsLists.get(position).getPicUrl())
                .into(holder.home_newgoodslist_picUrl);

        holder.home_newgoodslist_name.setText(newGoodsLists.get(position).getName());
        holder.home_newgoodslist_retailPrice.setText(String.valueOf(newGoodsLists.get(position).getRetailPrice()));

        // 绑定点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(newGoodsLists.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        return newGoodsLists.size();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView home_newgoodslist_picUrl;
        TextView home_newgoodslist_name;
        TextView home_newgoodslist_retailPrice;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            home_newgoodslist_picUrl = itemView.findViewById(R.id.home_newgoodslist_picUrl);
            home_newgoodslist_name = itemView.findViewById(R.id.home_newgoodslist_name);
            home_newgoodslist_retailPrice = itemView.findViewById(R.id.home_newgoodslist_retailPrice);
        }
    }
}
